<template>
  <div class="register">
    <!-- 导航栏 -->
    <NavBar
      title="注册"
      :left-arrow="true"
      @click-left="onBack"
      class="register__navbar"
    />

    <!-- 注册表单 -->
    <div class="register__container">
      <!-- Logo -->
      <div class="register__logo">
        <img src="/logo.png" alt="苒兴教育" class="register__logo-img" />
        <h1 class="register__title">注册账号</h1>
        <p class="register__subtitle">加入苒兴教育，开启学习之旅</p>
      </div>

      <!-- 注册步骤 -->
      <van-steps :active="currentStep" class="register__steps">
        <van-step>验证手机</van-step>
        <van-step>设置密码</van-step>
        <van-step>完善信息</van-step>
      </van-steps>

      <!-- 步骤1：验证手机号 -->
      <div v-if="currentStep === 0" class="register__step">
        <van-form @submit="onPhoneSubmit" class="register__form">
          <!-- 手机号 -->
          <van-field
            v-model="form.phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            :rules="phoneRules"
            left-icon="phone-o"
            maxlength="11"
            type="tel"
          />
          
          <!-- 验证码 -->
          <van-field
            v-model="form.code"
            name="code"
            label="验证码"
            placeholder="请输入验证码"
            :rules="codeRules"
            left-icon="shield-o"
            maxlength="6"
            type="number"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                :disabled="!canSendSms || smsCountdown > 0"
                :loading="sendingSms"
                @click="sendSmsCode"
                class="register__sms-btn"
              >
                {{ smsCountdown > 0 ? `${smsCountdown}s后重发` : '发送验证码' }}
              </van-button>
            </template>
          </van-field>
          
          <!-- 下一步按钮 -->
          <van-button
            type="primary"
            size="large"
            :loading="loading"
            native-type="submit"
            class="register__submit"
          >
            下一步
          </van-button>
        </van-form>
      </div>

      <!-- 步骤2：设置密码 -->
      <div v-if="currentStep === 1" class="register__step">
        <van-form @submit="onPasswordSubmit" class="register__form">
          <!-- 密码 -->
          <van-field
            v-model="form.password"
            name="password"
            label="密码"
            placeholder="请设置登录密码"
            :rules="passwordRules"
            left-icon="lock"
            :type="showPassword ? 'text' : 'password'"
            :right-icon="showPassword ? 'eye-o' : 'closed-eye'"
            @click-right-icon="showPassword = !showPassword"
          />
          
          <!-- 确认密码 -->
          <van-field
            v-model="form.confirmPassword"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入密码"
            :rules="confirmPasswordRules"
            left-icon="lock"
            :type="showConfirmPassword ? 'text' : 'password'"
            :right-icon="showConfirmPassword ? 'eye-o' : 'closed-eye'"
            @click-right-icon="showConfirmPassword = !showConfirmPassword"
          />
          
          <!-- 密码强度 -->
          <div class="register__password-strength">
            <div class="register__password-strength-label">密码强度：</div>
            <div class="register__password-strength-bar">
              <div 
                class="register__password-strength-fill"
                :class="`register__password-strength-fill--${passwordStrength.level}`"
                :style="{ width: passwordStrength.percent + '%' }"
              ></div>
            </div>
            <div class="register__password-strength-text">{{ passwordStrength.text }}</div>
          </div>
          
          <!-- 按钮组 -->
          <div class="register__buttons">
            <van-button
              size="large"
              @click="currentStep--"
              class="register__back"
            >
              上一步
            </van-button>
            <van-button
              type="primary"
              size="large"
              :loading="loading"
              native-type="submit"
              class="register__submit"
            >
              下一步
            </van-button>
          </div>
        </van-form>
      </div>

      <!-- 步骤3：完善信息 -->
      <div v-if="currentStep === 2" class="register__step">
        <van-form @submit="onInfoSubmit" class="register__form">
          <!-- 姓名 -->
          <van-field
            v-model="form.name"
            name="name"
            label="姓名"
            placeholder="请输入真实姓名"
            :rules="nameRules"
            left-icon="contact"
            maxlength="20"
          />
          
          <!-- 性别 -->
          <van-field
            v-model="form.gender"
            name="gender"
            label="性别"
            placeholder="请选择性别"
            readonly
            is-link
            left-icon="friends-o"
            @click="showGenderPicker = true"
          />
          
          <!-- 生日 -->
          <van-field
            v-model="form.birthday"
            name="birthday"
            label="生日"
            placeholder="请选择生日"
            readonly
            is-link
            left-icon="calendar-o"
            @click="showDatePicker = true"
          />
          
          <!-- 学校 -->
          <van-field
            v-model="form.school"
            name="school"
            label="学校"
            placeholder="请输入学校名称（选填）"
            left-icon="home-o"
            maxlength="50"
          />
          
          <!-- 按钮组 -->
          <div class="register__buttons">
            <van-button
              size="large"
              @click="currentStep--"
              class="register__back"
            >
              上一步
            </van-button>
            <van-button
              type="primary"
              size="large"
              :loading="loading"
              native-type="submit"
              class="register__submit"
            >
              完成注册
            </van-button>
          </div>
        </van-form>
      </div>

      <!-- 登录链接 -->
      <div class="register__login">
        <span>已有账号？</span>
        <span class="register__login-link" @click="onLogin">立即登录</span>
      </div>

      <!-- 协议 -->
      <div class="register__agreement">
        <van-checkbox v-model="agreeTerms" icon-size="14px">
          我已阅读并同意
          <span class="register__agreement-link" @click="onUserAgreement">《用户协议》</span>
          和
          <span class="register__agreement-link" @click="onPrivacyPolicy">《隐私政策》</span>
        </van-checkbox>
      </div>
    </div>

    <!-- 性别选择器 -->
    <van-popup v-model:show="showGenderPicker" position="bottom">
      <van-picker
        :columns="genderColumns"
        @confirm="onGenderConfirm"
        @cancel="showGenderPicker = false"
      />
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        v-model="selectedDate"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import NavBar from '@/components/common/NavBar.vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 当前步骤
const currentStep = ref(0)

// 表单数据
const form = ref({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
  name: '',
  gender: '',
  birthday: '',
  school: ''
})

// 表单状态
const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const agreeTerms = ref(false)

// 短信相关
const sendingSms = ref(false)
const smsCountdown = ref(0)
let smsTimer = null

// 选择器状态
const showGenderPicker = ref(false)
const showDatePicker = ref(false)
const selectedDate = ref(new Date())

// 性别选项
const genderColumns = [
  { text: '男', value: 'male' },
  { text: '女', value: 'female' }
]

// 日期范围
const minDate = new Date(1950, 0, 1)
const maxDate = new Date()

// 表单验证规则
const phoneRules = [
  { required: true, message: '请输入手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
]

const codeRules = [
  { required: true, message: '请输入验证码' },
  { pattern: /^\d{6}$/, message: '请输入6位数字验证码' }
]

const passwordRules = [
  { required: true, message: '请输入密码' },
  { min: 6, message: '密码至少6位' },
  { max: 20, message: '密码最多20位' }
]

const confirmPasswordRules = [
  { required: true, message: '请再次输入密码' },
  {
    validator: (value) => {
      if (value !== form.value.password) {
        return '两次输入的密码不一致'
      }
      return true
    }
  }
]

const nameRules = [
  { required: true, message: '请输入姓名' },
  { min: 2, message: '姓名至少2个字符' }
]

// 是否可以发送短信
const canSendSms = computed(() => {
  return /^1[3-9]\d{9}$/.test(form.value.phone)
})

// 密码强度
const passwordStrength = computed(() => {
  const password = form.value.password
  if (!password) {
    return { level: 'weak', percent: 0, text: '' }
  }
  
  let score = 0
  let level = 'weak'
  let text = '弱'
  
  // 长度
  if (password.length >= 6) score += 1
  if (password.length >= 8) score += 1
  
  // 包含数字
  if (/\d/.test(password)) score += 1
  
  // 包含小写字母
  if (/[a-z]/.test(password)) score += 1
  
  // 包含大写字母
  if (/[A-Z]/.test(password)) score += 1
  
  // 包含特殊字符
  if (/[^\w\s]/.test(password)) score += 1
  
  if (score >= 4) {
    level = 'strong'
    text = '强'
  } else if (score >= 2) {
    level = 'medium'
    text = '中'
  }
  
  return {
    level,
    percent: Math.min(score * 20, 100),
    text
  }
})

// 返回上一页
const onBack = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  } else {
    router.back()
  }
}

// 步骤1：验证手机号
const onPhoneSubmit = async () => {
  if (!agreeTerms.value) {
    showToast('请先同意用户协议和隐私政策')
    return
  }

  loading.value = true
  try {
    // 验证手机号和验证码
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    
    showToast('验证成功')
    currentStep.value = 1
  } catch (error) {
    showToast(error.message || '验证失败')
  } finally {
    loading.value = false
  }
}

// 步骤2：设置密码
const onPasswordSubmit = async () => {
  loading.value = true
  try {
    // 验证密码
    await new Promise(resolve => setTimeout(resolve, 500))
    
    currentStep.value = 2
  } catch (error) {
    showToast(error.message || '设置失败')
  } finally {
    loading.value = false
  }
}

// 步骤3：完善信息
const onInfoSubmit = async () => {
  loading.value = true
  try {
    await userStore.register({
      phone: form.value.phone,
      password: form.value.password,
      name: form.value.name,
      gender: form.value.gender,
      birthday: form.value.birthday,
      school: form.value.school
    })
    
    showDialog({
      title: '注册成功',
      message: '恭喜您成功注册苒兴教育账号！',
      confirmButtonText: '立即登录'
    }).then(() => {
      router.replace('/login')
    })
  } catch (error) {
    showToast(error.message || '注册失败')
  } finally {
    loading.value = false
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!canSendSms.value) {
    showToast('请输入正确的手机号')
    return
  }

  sendingSms.value = true
  try {
    // 这里调用发送短信的API
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    
    showToast('验证码已发送')
    
    // 开始倒计时
    smsCountdown.value = 60
    smsTimer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(smsTimer)
        smsTimer = null
      }
    }, 1000)
  } catch (error) {
    showToast(error.message || '发送失败')
  } finally {
    sendingSms.value = false
  }
}

// 性别选择确认
const onGenderConfirm = ({ selectedOptions }) => {
  form.value.gender = selectedOptions[0].text
  showGenderPicker.value = false
}

// 日期选择确认
const onDateConfirm = () => {
  const year = selectedDate.value.getFullYear()
  const month = String(selectedDate.value.getMonth() + 1).padStart(2, '0')
  const day = String(selectedDate.value.getDate()).padStart(2, '0')
  form.value.birthday = `${year}-${month}-${day}`
  showDatePicker.value = false
}

// 登录
const onLogin = () => {
  router.push('/login')
}

// 用户协议
const onUserAgreement = () => {
  router.push('/user-agreement')
}

// 隐私政策
const onPrivacyPolicy = () => {
  router.push('/privacy-policy')
}

// 页面初始化
onMounted(() => {
  // 如果已经登录，直接跳转
  if (userStore.isLoggedIn) {
    router.replace('/')
  }
})

// 页面销毁
onUnmounted(() => {
  if (smsTimer) {
    clearInterval(smsTimer)
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixins.scss';

.register {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  &__navbar {
    background: transparent;
    color: white;
    
    :deep(.navbar__title-text) {
      color: white;
    }
    
    :deep(.navbar__arrow) {
      color: white;
    }
  }

  &__container {
    padding: $spacing-xl $spacing-base;
    min-height: calc(100vh - $navbar-height);
  }

  &__logo {
    text-align: center;
    margin-bottom: $spacing-xl;
  }

  &__logo-img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin-bottom: $spacing-base;
  }

  &__title {
    font-size: $font-size-3xl;
    font-weight: $font-weight-bold;
    color: white;
    margin: 0 0 $spacing-xs 0;
  }

  &__subtitle {
    font-size: $font-size-base;
    color: rgba(255, 255, 255, 0.8);
    margin: 0;
  }

  &__steps {
    background: white;
    border-radius: $border-radius-xl;
    padding: $spacing-base;
    margin-bottom: $spacing-xl;
    
    :deep(.van-step__title) {
      font-size: $font-size-sm;
    }
  }

  &__step {
    background: white;
    border-radius: $border-radius-xl;
    margin-bottom: $spacing-xl;
  }

  &__form {
    padding: $spacing-base;
  }

  &__submit {
    margin-top: $spacing-lg;
    border-radius: $border-radius-xl;
    flex: 1;
  }

  &__back {
    margin-top: $spacing-lg;
    margin-right: $spacing-base;
    border-radius: $border-radius-xl;
    flex: 1;
  }

  &__buttons {
    display: flex;
    gap: $spacing-base;
  }

  &__sms-btn {
    border-radius: $border-radius-base;
    font-size: $font-size-xs;
  }

  &__password-strength {
    display: flex;
    align-items: center;
    gap: $spacing-xs;
    padding: $spacing-xs $spacing-base;
    font-size: $font-size-xs;
  }

  &__password-strength-label {
    color: $text-color-light;
    white-space: nowrap;
  }

  &__password-strength-bar {
    flex: 1;
    height: 4px;
    background: $gray-200;
    border-radius: 2px;
    overflow: hidden;
  }

  &__password-strength-fill {
    height: 100%;
    transition: all $transition-duration-base;
    
    &--weak {
      background: $danger-color;
    }
    
    &--medium {
      background: $warning-color;
    }
    
    &--strong {
      background: $success-color;
    }
  }

  &__password-strength-text {
    color: $text-color-light;
    white-space: nowrap;
  }

  &__login {
    text-align: center;
    color: white;
    font-size: $font-size-sm;
    margin-bottom: $spacing-lg;
  }

  &__login-link {
    color: #ffd700;
    cursor: pointer;
    text-decoration: underline;
  }

  &__agreement {
    text-align: center;
    
    :deep(.van-checkbox) {
      color: rgba(255, 255, 255, 0.8);
      font-size: $font-size-xs;
    }
  }

  &__agreement-link {
    color: #ffd700;
    cursor: pointer;
    text-decoration: underline;
  }
}

// 响应式适配
@include respond-below(480px) {
  .register {
    &__container {
      padding: $spacing-lg $spacing-base;
    }
    
    &__logo {
      margin-bottom: $spacing-lg;
    }
    
    &__title {
      font-size: $font-size-2xl;
    }
    
    &__buttons {
      flex-direction: column;
      
      .register__back {
        margin-right: 0;
        margin-bottom: $spacing-base;
      }
    }
  }
}
</style>